#!/usr/bin/python
# -*- coding: utf-8 -*-

from django.db import models

class PortClass:

    def __init__(self):
        self.status=False

    def setReactor(self,reactor):
        self.reactor=reactor

    def getReactor(self):
        return self.reactor


class Socket(models.Model):
    SOCKET_TYPES = (
            ('N','Network socket'),
            ('S','Serial socket'),
            )
    name = models.CharField(unique=True, max_length=240)
    type = models.CharField(max_length=2, choices = SOCKET_TYPES)
    properties=models.CharField(max_length=200)



        

    def __getSerialConnction__(self):
        return False

    def __getNetworkConnction__(self):
        from twisted.internet import reactor
        from twisted.internet.protocol import Protocol, Factory
        #from webloglib import hit_tag, log_fields

        class WebLog(Protocol):
            def connectionMade(self):
                print "Connected from", self.transport.client
                self.transport.write('<hits>')
            def dataReceived(self, data):
                newhits = LOG.readlines()
                if not newhits:
                    self.transport.write('<none/>')
                for hit in newhits:
                    self.transport.write(hit_tag % log_fields(hit))
            def connectionLost(self, reason):
                print "Disconnected from", self.transport.client

        self.factory = Factory()
        self.factory.protocol = WebLog
        reactor.listenTCP(self.__getPort__(), self.factory)
        try:
            
            self.setReactor(reactor.run())
            self.port.status=True
            self.socket=self.factory
            return self.factory
            
        except:
            return False
        
    def getSocket(self):
        try:
            return self.port
        except:
            return False
        
        
    def getStatus(self):
    
        if self.type=="N":
            try:
                return self.port.status
            except:
                self.port=PortClass()
                return self.port
        if self.type=="S":
            return self.port.status
    
    def close_connection(self):
        if self.type=="N":
            self.factory.doStop()
        if self.type=="S":
            pass
        

    def get_connection(self):
        if self.type=="N":
            self.port=PortClass()
            self.__getNetworkConnction__()
        if self.type=="S":
            self.__getSerialConnction__()


    def __getPort__(self):
        return int(self.name)

    
    class Meta:
        db_table = u'sockets'
        
    def get_properties(self):
        return self.properties.split(":")


#    def encode(self,codepage):
#        return "%s%s" % (self.get_properties()[0],self.name)





    def __unicode__(self):
        delimetr=""
        if self.type=="N":
            delimetr=":"
        return u"%s%s%s" % (self.get_properties()[0],delimetr,self.name)
